/*
 *    Copyright 2008-2009 The PoCo Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.asemantics.poco.parser.xml;

import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import com.asemantics.poco.parser.AbstractPocoParser;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: XmlPoCoParser.java 233 2009-12-19 23:12:38Z simone.tripodi@gmail.com $
 */
public final class XmlPoCoParser extends AbstractPocoParser {

    private static final SchemaFactory SCHEMA_FACTORY = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    private static final String SCHEMA_LOCATION = "poco.xsd";

    private static Schema POCO_SCHEMA = null;

    public XmlPoCoParser() {
        this(false);
    }

    public XmlPoCoParser(boolean validating) {
        this.digester = new Digester();

        if (validating) {
            synchronized (POCO_SCHEMA) {
                if (POCO_SCHEMA == null) {
                    try {
                        POCO_SCHEMA = SCHEMA_FACTORY.newSchema(this.getClass().getResource(SCHEMA_LOCATION));
                    } catch (SAXException e) {
                        throw new RuntimeException("Error while parsing XMLSchema.", e);
                    }
                }
            }
            this.digester.setXMLSchema(POCO_SCHEMA);
        }

        this.initRules();
    }

}
